package cn.itcast.item.controller;

import cn.itcast.hmall.dto.common.PageDTO;
import cn.itcast.hmall.dto.item.SearchItemDTO;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.item.mq.MqConstant;
import cn.itcast.item.service.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.Map;

@RestController
@RequestMapping("/item")
@Slf4j
public class ItemController {

    @Autowired
    private ItemService itemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 分页查询商品
     */
    @PostMapping("/list")
    public PageDTO<Item> list(@RequestBody Map params) {
        log.info("分页查询商品");
        return itemService.search(params);
    }

    /**
     * 根据id 查询商品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item getOne(@PathVariable("id")Long id){
        log.info("根据id{},查询商品信息",id);
        return itemService.getById(id);
    }

    /**
     * 添加商品
     */
    @PostMapping
    public void add(@RequestBody Item item) {
        log.info("新增商品{}",item.getId());
        itemService.save(item);
    }

    /**
     * 修改商品
     * @param item
     */
    @PutMapping
    public void update(@RequestBody Item item) {
        log.info("修改商品；{}",item.getId());
        itemService.updateById(item);
    }

    /**
     * 商品上架、下架
     */

    @PutMapping("/status/{id}/{status}")
    public void delete(@PathVariable("id")Long id,@PathVariable("status")Integer status) {
        log.info("商品{} {}",id,status==1?"上架":"下架");
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemService.updateById(item);
        //发送消息
        if (status==1){
            //添加文档
            rabbitTemplate.convertAndSend(MqConstant.ITEM_EXCHANGE,MqConstant.ITEM_INSERT_KEY,id);
        }else {
            //删除文档
            rabbitTemplate.convertAndSend(MqConstant.ITEM_EXCHANGE,MqConstant.ITEM_DELETE_KEY,id);
        }
    }

    /**
     * 删除商品
     * @param id
     */
    @DeleteMapping("/{id}")
    public void delete(@PathVariable("id")Long id) {
        //TODO: 使用逻辑删除
        log.info("删除商品{}",id);
        itemService.removeById(id);
    }

    /**
     * 修改库存
     */
    @PutMapping("/stock/{itemId}/{num}")
    public void stock(@PathVariable("itemId")Long itemId,@PathVariable("num")Integer num) {
        log.info("修改库存{}",itemId);
        itemService.updateStock(itemId,num);
        rabbitTemplate.convertAndSend(MqConstant.ITEM_EXCHANGE,MqConstant.ITEM_INSERT_KEY,itemId);
    }
}
